﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.BusinessEntity.YunZhiJia;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.ConstrainedExecution;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using static LiMinCRMPlugin.InterfaceDocking.PendingCollectionListModel;
using static System.Net.Mime.MediaTypeNames;

namespace LiMinCRMPlugin.InterfaceDocking
{
    /// <summary>
    /// 待认领清单审核插件
    /// </summary>
    /// <remarks>
    /// 功能：待认领清单在创建审核后自动传到CRM。
    /// 创建人：mey
    /// 创建日期：2024.3.22
    /// 修改信息（1）：修改人，修改日期，修改内容
    /// </remarks>
    /// 
    [Description("待认领清单审核同步至CRM")]
    [HotUpdate]
    public class PendingCollectionListToCRM : AbstractOperationServicePlugIn
    {
        //OnPreparePropertys 数据加载前，确保需要的属性被加载
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);

            //编码
            e.FieldKeys.Add("FBillNo");
            //流水号
            e.FieldKeys.Add("F_RDLV_SerialNumber");
            //组织
            e.FieldKeys.Add("F_RDLV_OrgId_83g");
            //交易日
            e.FieldKeys.Add("F_RDLV_TradingDay");
            //承兑票号
            e.FieldKeys.Add("F_RDLV_AcceptanceNumber");

            //交易金额
            e.FieldKeys.Add("F_RDLV_Amount");

            //同步CRM状态
            e.FieldKeys.Add("F_DEV_FSTATUS");
            //收款银行
            e.FieldKeys.Add("F_RDLV_ReceivingBank");
            //收款银行账号
            e.FieldKeys.Add("F_RDLV_Base_w5c");
            //结算方式
            e.FieldKeys.Add("F_RDLV_SettleType");
            //承兑签发日
            e.FieldKeys.Add("F_RDLV_CDQFR");
            //承兑到期日
            e.FieldKeys.Add("F_RDLV_CDDQR");


            //币别
            e.FieldKeys.Add("F_RDLV_CurrencyType");
            //付款方账户名称
            e.FieldKeys.Add("F_RDLV_PayerAccount");
            //付款方银行账号
            e.FieldKeys.Add("F_RDLV_PayerBankAccount");
            //付款方开户行
            e.FieldKeys.Add("F_RDLV_PayerOpenBank");
            //出票人
            e.FieldKeys.Add("F_RDLV_Drawer");
            //承兑人
            e.FieldKeys.Add("F_RDLV_Acceptor");
            //汇率
            e.FieldKeys.Add("F_QLTK_ExchangeRate");

            //汇率
            e.FieldKeys.Add("F_RDLV_CreatorId_6oq");
        }
        /// <summary>
        /// 事务结束后事件
        /// </summary>
        /// <param name="e"></param>
        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            base.AfterExecuteOperationTransaction(e);

            //读取全部的单据,for循环,转换成DynamicObject类型
            foreach (DynamicObject entity in e.DataEntitys)
            {
                DataTable dt = APISetting();
                string httpUrl = dt.Rows[0]["F_RDLV_URL"].ToString();
                string httpSystemId = dt.Rows[0]["F_RDLV_SystemId"].ToString();
                string httpPassword = dt.Rows[0]["F_RDLV_Password"].ToString();

                string UserAccount = "CRM";//用户账号
                //DynamicObject User = entity["F_RDLV_CreatorId_6oq"] as DynamicObject;//用户
                //if (User != null)
                //{
                //    UserAccount = Convert.ToString(User["UserAccount"]);
                //}



                string FSTATUS = Convert.ToString(entity["F_DEV_FSTATUS"]);//同步CRM状态 空-未同步，成功-同步成功，失败-同步失败
                string FID = Convert.ToString(entity["Id"]);//内码                      
                string Number = entity["BillNo"].ToString();//编码


                string SerialNumber = entity["F_RDLV_SerialNumber"].ToString();//流水号
                string TradingDay = "";
                if (entity["F_RDLV_TradingDay"] != null && entity["F_RDLV_TradingDay"].ToString() != "")
                {
                    TradingDay = Convert.ToDateTime(entity["F_RDLV_TradingDay"]).ToString("yyyy-MM-dd");//交易日 jyr
                }

                string AcceptanceNumber = entity["F_RDLV_AcceptanceNumber"].ToString();//承兑票号 cdph
                string PayerAccount = entity["F_RDLV_PayerAccount"].ToString();//付款方账户名称 fkfzhmc
                decimal Amount = Convert.ToDecimal(entity["F_RDLV_Amount"]);//交易金额 jyje
                DynamicObject SettleType = entity["F_RDLV_SettleType"] as DynamicObject;//结算方式 jsfs
                string SettleTypeNumber = "";//结算方式
                if (SettleType != null)
                {
                    SettleTypeNumber = Convert.ToString(SettleType["Number"]);//结算方式

                }


                DynamicObject Org = entity["F_RDLV_OrgId_83g"] as DynamicObject;//组织 公司代码 gsdm
                string OrgNumber = "";//使用组织编码
                if (Org != null)
                {
                    OrgNumber = Convert.ToString(Org["Number"]);//组织

                }
                string CDQFR = "";
                if (entity["F_RDLV_CDQFR"] != null && entity["F_RDLV_CDQFR"].ToString() != "")
                {
                    CDQFR = Convert.ToDateTime(entity["F_RDLV_CDQFR"]).ToString("yyyy-MM-dd");//承兑签发日   cdqfr  

                }
                string CDDQR = "";
                if (entity["F_RDLV_CDDQR"] != null && entity["F_RDLV_CDDQR"].ToString() != "")
                {
                    CDDQR = Convert.ToDateTime(entity["F_RDLV_CDDQR"]).ToString("yyyy-MM-dd");//承兑到期日   cddqr  

                }
                string PayerBankAccount = entity["F_RDLV_PayerBankAccount"].ToString();//付款方银行账号 fkfyxzh

                string PayerOpenBank = entity["F_RDLV_PayerOpenBank"].ToString();//付款方开户行 fkfkhx

                string Drawer = entity["F_RDLV_Drawer"].ToString();//出票人 cpr

                string Acceptor = entity["F_RDLV_Acceptor"].ToString();//承兑人 cdr


                DynamicObject CurrencyType = entity["F_RDLV_CurrencyType"] as DynamicObject;//币别 bb
                string CurrencyTypeNumber = "";//币别
                if (CurrencyType != null)
                {
                    CurrencyTypeNumber = Convert.ToString(CurrencyType["Name"]);//币别

                }
                DynamicObject ReceivingBank = entity["F_RDLV_ReceivingBank"] as DynamicObject;//收款银行 skyh
                string ReceivingBankNumber = "";//收款银行
                if (ReceivingBank != null)
                {
                    ReceivingBankNumber = Convert.ToString(ReceivingBank["Number"]);//收款银行

                }
                DynamicObject skyhzh1 = entity["F_RDLV_Base_w5c"] as DynamicObject;//收款银行帐号 skyhzh
                string skyhzh1Number = "";//收款银行帐号
                if (skyhzh1 != null)
                {
                    skyhzh1Number = Convert.ToString(skyhzh1["Id"]);//收款银行帐号

                }
                decimal ExchangeRate = Convert.ToDecimal(entity["F_QLTK_ExchangeRate"]);//汇率


                #region 插入更新赋值
                mainTable mainTable1 = new mainTable()
                {
                    yxlsbm = Number,//银行流水编码
                    lsh = SerialNumber,//流水号
                    jyr = TradingDay,//交易日  传入格式：yyyy-MM-dd
                    cdph = AcceptanceNumber,//承兑票号

                    fkfzhmc = PayerAccount,//付款方账户名称
                    jyje = Amount,//交易金额
                    jsfs = SettleTypeNumber,//结算方式
                    gsdm = OrgNumber,//公司代码
                    cdqfr = CDQFR,//承兑签发日 yyyy-MM-dd

                    cddqr = CDDQR,//承兑到期日 yyyy-MM-dd

                    fkfyxzh = PayerBankAccount,//付款方银行账号



                    fkfkhx = PayerOpenBank,//付款方开户行

                    cpr = Drawer,//出票人

                    cdr = Acceptor,//承兑人

                    bb = CurrencyTypeNumber,//币别


                    krlje = Amount,//可认领金额

                    skyh = ReceivingBankNumber,//收款银行

                    skyhzh = skyhzh1Number,//收款银行帐号

                    djnm = FID,//单据内码
                    hl = ExchangeRate //汇率
                };
                //操作人员信息
                operationinfo operationinfo1 = new operationinfo()
                {
                    operatorAbAb = UserAccount,
                    operationDate = DateTime.Now.ToString("yyyy-MM-dd"),
                    operationTime = DateTime.Now.ToString("HH:mm:ss")
                };

                String currentTimeTamp = getTimestamp();
                String md5Source = httpSystemId + httpPassword + currentTimeTamp;
                String md5OfStr = Md5(md5Source).ToLower();


                Header header1 = new Header()
                {
                    systemid = httpSystemId,
                    currentDateTime = currentTimeTamp,
                    Md5 = md5OfStr
                };

                Data data = new Data()
                {
                    operationinfo = operationinfo1,
                    mainTable = mainTable1
                };

                List<Data> datas = new List<Data>();
                datas.Add(data);


                DataHeader dataHeader = new DataHeader()
                {
                    data = datas,
                    header = header1
                };
                var json = JsonConvert.SerializeObject(dataHeader);
                json = json.ToString().Replace("operatorAbAb", "operator");
                #endregion

                #region 查询赋值
                PendingCollectionListSelectModel.mainTable mainTable2 = new PendingCollectionListSelectModel.mainTable()
                {
                    djnm = FID,
                };
                //操作人员信息
                PendingCollectionListSelectModel.operationinfo operationinfo2 = new PendingCollectionListSelectModel.operationinfo()
                {
                    operatorAbAb = UserAccount,

                };
                PendingCollectionListSelectModel.Header header2 = new PendingCollectionListSelectModel.Header()
                {
                    systemid = httpSystemId,
                    currentDateTime = currentTimeTamp,
                    Md5 = md5OfStr
                };
                PendingCollectionListSelectModel.DataHeader dataHeader1 = new PendingCollectionListSelectModel.DataHeader()
                {
                    operationinfo = operationinfo2,
                    mainTable = mainTable2,
                    header = header2
                };

                var jsonS = JsonConvert.SerializeObject(dataHeader1);
                jsonS = jsonS.ToString().Replace("operatorAbAb", "operator");
                #endregion

                //查询是否存在
                var httpJson = GlobalParameters.PostToPushGroupNews(httpUrl + "/cube/restful/interface/getDataByPK/select_Bank_Statement", jsonS);

                var arrresult = JsonConvert.DeserializeObject<SortedDictionary<string, object>>(httpJson);//转换
                var MainTable = JsonConvert.DeserializeObject<SortedDictionary<string, object>>(arrresult["result"].ToString());//转换


                if (MainTable.Count == 0)//
                {

                    //json = JsonConvert.SerializeObject(json);

                    var AddJson = GlobalParameters.PostToPushGroupNews(httpUrl + "/cube/restful/interface/saveOrUpdateModeData/create_Bank_Statement", json);

                    var Addresult = JsonConvert.DeserializeObject<GlobalParameters.ReturnJson>(AddJson);//转换


                    if (Addresult.status == "1")
                    {
                        #region 待认领清单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                        Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                        interfaceLog.FBILLNO = Number;
                        interfaceLog.FBILLID = FID;
                        interfaceLog.FDATE = System.DateTime.Now;
                        interfaceLog.FINTERNAME = "待认领清单";
                        interfaceLog.FInvokeType = "待认领清单新增";
                        interfaceLog.Ftoken = "";
                        interfaceLog.FSTATUS = "成功";
                        interfaceLog.FRequsetData = json.ToString().Replace("'", "");
                        interfaceLog.FReturnData = AddJson.ToString().Replace("'", "");
                        interfaceLog.FRequest = json.ToString().Replace("'", "");
                        interfaceLog.FReturn = AddJson.ToString().Replace("'", "");
                        string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                        List<string> sqlList = new List<string>();
                        if (!string.IsNullOrEmpty(LogSql))
                        {
                            sqlList.Add(LogSql);
                        }
                        //更新单据
                        string updateSql = string.Format(@"/*dialect*/ update RDLV_t_PendingCollection set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                        sqlList.Add(updateSql);
                        DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                        IOperationResult operationResult = new OperationResult();

                        operationResult.OperateResult.Add(new OperateResult()
                        {
                            SuccessStatus = true,
                            Message = string.Format("待认领清单数据上传成功！"),
                            MessageType = MessageType.Warning,
                            PKValue = 0,
                        });
                        this.OperationResult.MergeResult(operationResult);

                        #endregion
                    }
                    else
                    {
                        #region 待认领清单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                        Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                        interfaceLog.FBILLNO = Number;
                        interfaceLog.FBILLID = FID;
                        interfaceLog.FDATE = System.DateTime.Now;
                        interfaceLog.FINTERNAME = "待认领清单";
                        interfaceLog.FInvokeType = "待认领清单新增";
                        interfaceLog.Ftoken = "";
                        interfaceLog.FSTATUS = "失败";
                        interfaceLog.FRequsetData = json.ToString().Replace("'", "");
                        interfaceLog.FReturnData = AddJson.ToString().Replace("'", "");
                        interfaceLog.FRequest = json.ToString().Replace("'", "");
                        interfaceLog.FReturn = AddJson.ToString().Replace("'", "");
                        string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                        List<string> sqlList = new List<string>();
                        if (!string.IsNullOrEmpty(LogSql))
                        {
                            sqlList.Add(LogSql);
                        }
                        //更新单据
                        string updateSql = string.Format(@"/*dialect*/ update RDLV_t_PendingCollection set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                        sqlList.Add(updateSql);

                        DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                        IOperationResult operationResult = new OperationResult();

                        operationResult.OperateResult.Add(new OperateResult()
                        {
                            SuccessStatus = false,
                            Message = string.Format("待认领清单数据上传失败，请手工同步！"),
                            MessageType = MessageType.Warning,
                            PKValue = 0,
                        });
                        this.OperationResult.MergeResult(operationResult);


                        #endregion
                    }

                }
                else
                {
                    //cube / restful /interface/saveOrUpdateModeData/update_Transportation_area
                    var UpdateJson = GlobalParameters.PostToPushGroupNews(httpUrl + "/cube/restful/interface/saveOrUpdateModeData/update_Bank_Statement", json);

                    var Updateresult = JsonConvert.DeserializeObject<GlobalParameters.ReturnJson>(UpdateJson);//转换

                    if (Updateresult.status == "1")
                    {
                        #region 待认领清单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                        Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                        interfaceLog.FBILLNO = Number;
                        interfaceLog.FBILLID = FID;
                        interfaceLog.FDATE = System.DateTime.Now;
                        interfaceLog.FINTERNAME = "待认领清单";
                        interfaceLog.FInvokeType = "待认领清单更新";
                        interfaceLog.Ftoken = "";
                        interfaceLog.FSTATUS = "成功";
                        interfaceLog.FRequsetData = json.ToString().Replace("'","");
                        interfaceLog.FReturnData = UpdateJson.ToString().Replace("'", "");
                        interfaceLog.FRequest = json.ToString().Replace("'", "");
                        interfaceLog.FReturn = UpdateJson.ToString().Replace("'", "");
                        string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                        List<string> sqlList = new List<string>();
                        if (!string.IsNullOrEmpty(LogSql))
                        {
                            sqlList.Add(LogSql);
                        }
                        //更新单据
                        string updateSql = string.Format(@"/*dialect*/ update RDLV_t_PendingCollection set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                        sqlList.Add(updateSql);
                        DBServiceHelper.ExecuteBatch(this.Context, sqlList);

                        IOperationResult operationResult = new OperationResult();

                        operationResult.OperateResult.Add(new OperateResult()
                        {
                            SuccessStatus = true,
                            Message = string.Format("待认领清单数据更新成功！"),
                            MessageType = MessageType.Warning,
                            PKValue = 0,
                        });
                        this.OperationResult.MergeResult(operationResult);
                        #endregion
                    }
                    else
                    {
                        #region 待认领清单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                        Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                        interfaceLog.FBILLNO = Number;
                        interfaceLog.FBILLID = FID;
                        interfaceLog.FDATE = System.DateTime.Now;
                        interfaceLog.FINTERNAME = "待认领清单";
                        interfaceLog.FInvokeType = "待认领清单更新";
                        interfaceLog.Ftoken = "";
                        interfaceLog.FSTATUS = "失败";
                        interfaceLog.FRequsetData = json.ToString().Replace("'", ""); ;
                        interfaceLog.FReturnData = UpdateJson.ToString().Replace("'", ""); ;
                        interfaceLog.FRequest = json.ToString().Replace("'", ""); ;
                        interfaceLog.FReturn = UpdateJson.ToString().Replace("'", ""); ;
                        string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                        List<string> sqlList = new List<string>();
                        if (!string.IsNullOrEmpty(LogSql))
                        {
                            sqlList.Add(LogSql);
                        }
                        //更新单据
                        string updateSql = string.Format(@"/*dialect*/ update RDLV_t_PendingCollection set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                        sqlList.Add(updateSql);

                        DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                        IOperationResult operationResult = new OperationResult();

                        operationResult.OperateResult.Add(new OperateResult()
                        {
                            SuccessStatus = false,
                            Message = string.Format("待认领清单数据上传失败，请手工同步！"),
                            MessageType = MessageType.Warning,
                            PKValue = 0,
                        });
                        this.OperationResult.MergeResult(operationResult);


                        #endregion
                    }

                }


            }
        }

        /// <summary>
        /// api配置
        /// </summary>
        public DataTable APISetting()
        {
            string Sql = string.Format(@"select * from RDLV_t_CRMInterface");
            return DBServiceHelper.ExecuteDataSet(this.Context, Sql).Tables[0];

        }

        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String Md5(string s)
        {
            char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(s);
            byte[] result = md5.ComputeHash(inputBytes);
            int j = result.Length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++)
            {
                byte byte0 = result[i];
                str[k++] = hexDigits[byte0 >> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        }
        /**
       * 获取时间戳   格式如：19990101235959
       * @return
       */
        public static String getTimestamp()
        {

            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Replace("-", "").Replace(":", "").Replace(" ", "").Replace("/", "");
        }


    }
}
